package com.cgsd.heyu.ui.home.fragment;

import android.content.Context;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.android.library.utils.ToastHelper;
import com.android.library.wedgets.TitleBarView;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.ui.BaseFragment;
import com.cgsd.heyu.ui.task.MyTaskActivity;
import com.cgsd.heyu.ui.task.TaskChildFragment;
import com.cgsd.heyu.ui.task.adapter.TabAdapter;
import com.cgsd.heyu.ui.task.vo.TaskListVo;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.utils.StringUtils;
import com.cgsd.heyu.widgets.dialog.TaskClassifyPopup;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;

/**
 * Author: sky on 2021/3/1 11:13
 * Email: xcode126@126.com
 * Desc: 任务
 */
public class TaskFragment extends BaseFragment implements TitleBarView.TitleBarClickListener, View.OnClickListener {

    private MagicIndicator mIndicator;
    private TitleBarView mTitleBarView;
    private ViewPager mViewPager;
    private TabAdapter adapter;
    private LinearLayout llOption;
    private List<TaskListVo.CatelistBean> catelist;
    private TaskClassifyPopup classifyPopup;

    public static TaskFragment newInstance() {
        return new TaskFragment();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_task;
    }

    @Override
    protected void initView() {
        llOption = findViewById(R.id.ll_option);
        mTitleBarView = findViewById(R.id.title_bar);
        mViewPager = findViewById(R.id.mViewPager);
        mIndicator = findViewById(R.id.mIndicator);
        EditText mEtSearch = findViewById(R.id.et_search);
        findViewById(R.id.ll_classify).setOnClickListener(this);

        mTitleBarView.setRightText(getString(R.string.a_my_task));
        mTitleBarView.setRightTextSize(16);
        mTitleBarView.setTitleBarClickListener(this);

        StringUtils.editTextSearchAction(mEtSearch, new StringUtils.OnEditTextSearchListener() {
            @Override
            public void onEditorAction(String content) {
                showToast("搜索");
            }
        });
    }

    @Override
    protected void initData() {
        getTaskCategory();
    }

    /**
     * 初始化菜单栏
     *
     * @param taglist
     */
    private void initTitleIndicator(List<TaskListVo.TaglistBean> taglist) {
        CommonNavigator titleNavigator = new CommonNavigator(mContext);
        titleNavigator.setAdjustMode(true);//true 自适应居中、false 反之
        titleNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return taglist.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                TaskListVo.TaglistBean bean = taglist.get(index);
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setText(bean.name);
                simplePagerTitleView.setPadding(0, 0, 0, 0);
                simplePagerTitleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(mContext, R.color.textMain));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(mContext, R.color.app_color));

                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(ContextCompat.getColor(mContext, R.color.app_color));
                return linePagerIndicator;
            }
        });
        mIndicator.setNavigator(titleNavigator);
        ViewPagerHelper.bind(mIndicator, mViewPager);
    }

    /**
     * get fragments
     *
     * @param taglist
     * @return
     */
    private List<BaseFragment> initFragments(List<TaskListVo.TaglistBean> taglist) {
        List<BaseFragment> list = new ArrayList<>();
        for (TaskListVo.TaglistBean cate : taglist) {
            if (cate.id > 0) {
                list.add(TaskChildFragment.newInstance(cate.id));
            }
        }
        return list;
    }

    @Override
    public void leftClick() {

    }

    @Override
    public void rightClick() {
        startActivity(MyTaskActivity.getIntent(mContext));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_classify:
                optionDialog();
                break;
        }
    }

    /**
     * 筛选分类弹窗
     */
    private void optionDialog() {
        if (catelist != null && catelist.size() > 0) {
            if (classifyPopup == null) {
                classifyPopup = new TaskClassifyPopup(mContext, bean -> transitChild(0, bean.id));
            }
            classifyPopup.show(llOption, catelist);
        } else {
            showToast("暂无分类信息");
        }
    }

    /**
     * get category
     */
    public void getTaskCategory() {
        RequestBody requestBody = new RequestParams()
                .putUid()
                .put("page", 1)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .getTaskList(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<TaskListVo>>() {
                    @Override
                    public void onSuccess(BaseResponse<TaskListVo> baseResponse) {
                        processTaskCategory(baseResponse.getBizBody());
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        handleErrorAction(error);
                    }
                });
    }

    /**
     * process task category
     *
     * @param listVo
     */
    private void processTaskCategory(TaskListVo listVo) {
        this.catelist = listVo.catelist;
        catelist.add(new TaskListVo.CatelistBean(-1,"重置"));
        List<BaseFragment> list = initFragments(listVo.taglist);
        adapter = new TabAdapter(getChildFragmentManager(), list);
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(list.size());
        initTitleIndicator(listVo.taglist);
    }

    /**
     * 切换子界面
     *
     * @param index
     * @param t
     */
    private void transitChild(int index, Object t) {
//        if (adapter != null && index < adapter.getCount() && index >= 0) {
//            Fragment item = adapter.getItem(index);
//            if (item instanceof WrapperSendFragment) {
//                ((WrapperSendFragment) item).onRefresh(t);
//            }
//        }
        for (int i = 0; i < adapter.getCount(); i++) {
            Fragment item = adapter.getItem(i);
            if (item instanceof WrapperSendFragment) {
                ((WrapperSendFragment) item).onRefresh(t);
            }
        }
    }
}
